import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' show DataCell, DataColumn;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import '../../components/data_table.dart';
import '../../model/semester_model.dart';
import '../../utils/date_utils.dart';
import '../app/app_dict_data.dart';
import 'school_semester_view_add.dart';
import 'school_semester_view_model.dart';

///学校:学期列表
class SchoolSemesterViewList extends StatefulWidget {
  final String schoolId;

  const SchoolSemesterViewList({super.key, required this.schoolId});

  @override
  State<StatefulWidget> createState() => _SchoolSemesterViewListState();
}

class _SchoolSemesterViewListState extends State<SchoolSemesterViewList> {
  final queryFormKey = GlobalKey<FormState>();
  final tableKey = GlobalKey<DataTableState<SemesterItemRes>>();

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<SchoolSemesterViewModel>();
    model.loadInit(afterHandler: () => query(model));
  }

  void query(final SchoolSemesterViewModel model) =>
      model.query(widget.schoolId);

  Widget buildQueryForm(final SchoolSemesterViewModel model) {
    Widget buildField(SchoolSemesterQueryField field,
        Widget Function(TextEditingController? c, String label) handler) {
      final label = field.label;
      final controller = model.getController(field);
      final child = handler.call(controller, label);
      return SizedBox(
        width: 128.w,
        child: InfoLabel(
          label: label,
          child: child,
        ),
      );
    }

    return Form(
      key: queryFormKey,
      child: Wrap(
        spacing: 5.w,
        children: [
          //状态
          buildField(
            SchoolSemesterQueryField.status,
            (ctr, label) => ComboboxFormField(
              placeholder: Text(label),
              items: model.statusOpts,
              onChanged: (val) => ctr?.text = val ?? '',
            ),
          ),
        ],
      ),
    );
  }

  Widget buildQueryBars(final SchoolSemesterViewModel model) => Wrap(
        spacing: 2.w,
        children: [
          //查询
          buttons.query(onPressed: () => query(model)),
          //重置
          buttons.reset(onPressed: () {
            queryFormKey.currentState?.reset();
            model.cleanQueryFields();
            query(model);
          }),
          //新增
          buttons.add(onPressed: () => addHandler(model)),
        ],
      );

  void popHandler(final bool ret) => context.pop<bool>(ret);

  void addHandler(final SchoolSemesterViewModel model) async {
    //新增处理
    final ret = await showDialog<bool>(
        context: context,
        builder: (context) {
          final checkedSemesters = <String>[];
          final size = MediaQuery.sizeOf(context);
          final padding = PageHeader.horizontalPadding(context);
          return ContentDialog(
            title: const Text('添加学年学期'),
            constraints: BoxConstraints(
              maxWidth: size.width - padding * 2,
              maxHeight: size.height - padding * 2,
            ),
            content: ChangeNotifierProvider.value(
              value: model,
              builder: (context, _) => SchoolSemesterViewAdd(
                schoolId: widget.schoolId,
                checkedSemesters: checkedSemesters,
              ),
            ),
            actions: [
              buttons.cancel(
                onPressed: () {
                  checkedSemesters.clear();
                  return popHandler(false);
                },
              ),
              buttons.submit(
                onPressed: () {
                  final checked = checkedSemesters;
                  if (checked.isEmpty) {
                    popHandler(false);
                    return;
                  }
                  //保存数据
                  model.onSaveHandler(
                    widget.schoolId,
                    checked,
                    () => popHandler(true),
                  );
                },
              ),
            ],
          );
        });
    //关闭弹框
    if (ret ?? false) {
      //重新加载数据
      query(model);
    }
  }

  @override
  Widget build(final BuildContext context) => Consumer<SchoolSemesterViewModel>(
        builder: (context, model, _) => ScaffoldPage.scrollable(
          header: Column(children: [
            PageHeader(title: const Text('学年学期')),
            Padding(
              padding: () {
                final padding = PageHeader.horizontalPadding(context);
                return EdgeInsetsDirectional.symmetric(horizontal: padding);
              }(),
              child: Row(children: [
                //查询条件
                buildQueryForm(model),
                //占位
                Expanded(child: Container()),
                //查询按钮
                buildQueryBars(model),
              ]),
            ),
            SizedBox(height: 15.h),
          ]),
          children: [
            //数据列表
            buildTable(model),
          ],
        ),
      );

  Widget buildTable(final SchoolSemesterViewModel model) {
    final labels = <String>['编码', '名称', '开始日期', '结束日期', '状态', '操作'];
    DataCell buildCell(String? Function() handler) => DataCell(Text(
          handler.call() ?? '',
          softWrap: false,
          overflow: TextOverflow.ellipsis,
        ));
    return DataTable<SemesterItemRes>(
      key: tableKey,
      model: model.queryModel,
      columns: labels.map((label) => DataColumn(label: Text(label))).toList(),
      onLoadData: () => query(model),
      onRowCallback: (row) => [
        //编码
        buildCell(() => row.code),
        //名称
        buildCell(() => row.title),
        //开始日期
        buildCell(() => dateUtils.format('yyyy-MM-dd', row.start)),
        //结束日期
        buildCell(() => dateUtils.format('yyyy-MM-dd', row.end)),
        //状态
        buildCell(() => appDictData.getLabel('status', row.status)),
        //操作
        DataCell(OverflowBar(
          spacing: 2.w,
          children: [
            //删除
            buttons.delete(
              onPressed: () => model.onDeleteHandler(
                schoolId: widget.schoolId,
                id: row.id,
              ),
            ),
          ],
        )),
      ],
    );
  }
}
